﻿#include "Purchase_Ticket_Search.h"
#include "Purchase_Ticket_Process.h"
#include <Global_Class.h>
#include <QMessageBox>
#include <QDate>
#include <QTableWidgetItem>
#include <algorithm>

Purchase_Ticket_Search::Purchase_Ticket_Search(QWidget *parent,bool enableSearchOrPurchase)
	: QDialog(parent)
{
	ui.setupUi(this);
	// 设置日期选择器只能选今天及往后31天的日期
	QDate today = QDate::currentDate();
	ui.dateEdit->setCalendarPopup(true);
	ui.dateEdit->setDate(today);
	ui.dateEdit->setMinimumDate(today);
	ui.dateEdit->setMaximumDate(today.addDays(31));
	int column = enableSearchOrPurchase ? 9 : 10;
	ui.ticketResultTable->setColumnCount(column);
	if (enableSearchOrPurchase == false)
		ui.ticketResultTable->setHorizontalHeaderLabels({ "车次", "出发站", "到达站", "发车时间", "到达时间", "商务余座", "一等余座", "二等余座", "票价", "操作" });
	else 
		ui.ticketResultTable->setHorizontalHeaderLabels({ "车次", "出发站", "到达站", "发车时间", "到达时间", "商务余座", "一等余座", "二等余座", "票价"});
	connect(ui.EnterBtn, &QPushButton::clicked, this, &Purchase_Ticket_Search::onQueryTickets);

}

Purchase_Ticket_Search::~Purchase_Ticket_Search()
{
}

void Purchase_Ticket_Search::onQueryTickets()
{
	// 每次查询前刷新座位占用信息，确保余票数据最新
	allData->SeatOccupy_ReadFromFile("seat_occupy.txt");
	// 设置窗口大小自适应表格内容
	this->resize(1200, 600);
	ui.ticketResultTable->setRowCount(0);
	// 设置表头和自适应票价列宽
	ui.ticketResultTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
	ui.ticketResultTable->horizontalHeader()->setSectionResizeMode(8, QHeaderView::ResizeToContents); // 票价列自适应
	ui.ticketResultTable->horizontalHeader()->setStretchLastSection(true);
	ui.ticketResultTable->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);

	// 使用QDateEdit获取日期
	QString date = ui.dateEdit->date().toString("yyyy-MM-dd");
	QString startStation = ui.start_station->currentText();
	QString endStation = ui.end_station->currentText();
	QString trainCode = ui.trainCodeLineEdit->text().trimmed();

	if (startStation == endStation) {
		QMessageBox::warning(this, "查询条件错误", "起点站和终点站不能相同！");
		return;
	}

	// 获取站点ID
	int startStationId = -1, endStationId = -1;
	for (const auto& station : allData->stationsQueue) {
		if (station.getName() == startStation.toStdString()) startStationId = station.getStationId();
		if (station.getName() == endStation.toStdString()) endStationId = station.getStationId();
	}
	if (startStationId == -1 || endStationId == -1) {
		QMessageBox::warning(this, "查询条件错误", "站点选择有误！");
		return;
	}

	bool found = false;
	for (const auto& train : allData->trainQueue) {
		if (!trainCode.isEmpty() && train.getTrainCode() != trainCode.toStdString()) continue;

		// 查找该车次的时刻表
		std::vector<const train_schedule*> schedules;
		for (const auto& sch : allData->trainSchedules) {
			if (sch.getTrainId() == train.getTrainId()) {
				schedules.push_back(&sch);
			}
		}
		std::sort(schedules.begin(), schedules.end(), [](const train_schedule* a, const train_schedule* b) {
			return a->getStopOrder() < b->getStopOrder();
		});
		int startIdx = -1, endIdx = -1;
		for (size_t i = 0; i < schedules.size(); ++i) {
			if (schedules[i]->getStationId() == startStationId) startIdx = static_cast<int>(i);
			if (schedules[i]->getStationId() == endStationId) endIdx = static_cast<int>(i);
		}
		if (startIdx == -1 || endIdx == -1 || startIdx >= endIdx) continue;

		// 统计各座型余座数（基于seatOccupy机制）
		int businessRemain = 0, firstRemain = 0, secondRemain = 0;
		for (const auto& seat : allData->seatsQueue) {
			if (seat.getTrainId() == train.getTrainId()) {
				int seatId = seat.getSeatId();
				bool available = allData->IsSeatAvailable(date.toStdString(), train.getTrainId(), seatId, startStationId, endStationId);
				if (available) {
					if (seat.getSeatType() == "商务座") businessRemain++;
					else if (seat.getSeatType() == "一等座") firstRemain++;
					else if (seat.getSeatType() == "二等座") secondRemain++;
				}
			}
		}
		if (businessRemain <= 0 && firstRemain <= 0 && secondRemain <= 0) continue;

		// 获取时间信息
		QString departTime = QString::fromStdString(schedules[startIdx]->getDepartTime());
		QString arriveTime = QString::fromStdString(schedules[endIdx]->getArrivalTime());
		// 票价
		double priceBusiness = AllData::CalculateTicketPrice(startStationId, endStationId, "商务座", allData->stationsQueue);
		double priceFirst = AllData::CalculateTicketPrice(startStationId, endStationId, "一等座", allData->stationsQueue);
		double priceSecond = AllData::CalculateTicketPrice(startStationId, endStationId, "二等座", allData->stationsQueue);
		QString priceStr = QString("商务座:%1 一等座:%2 二等座:%3")
			.arg(priceBusiness < 0 ? "-" : QString::number(priceBusiness, 'f', 2))
			.arg(priceFirst < 0 ? "-" : QString::number(priceFirst, 'f', 2))
			.arg(priceSecond < 0 ? "-" : QString::number(priceSecond, 'f', 2));

		int row = ui.ticketResultTable->rowCount();
		ui.ticketResultTable->insertRow(row);
		ui.ticketResultTable->setItem(row, 0, new QTableWidgetItem(QString::fromStdString(train.getTrainCode())));
		ui.ticketResultTable->setItem(row, 1, new QTableWidgetItem(startStation));
		ui.ticketResultTable->setItem(row, 2, new QTableWidgetItem(endStation));
		ui.ticketResultTable->setItem(row, 3, new QTableWidgetItem(departTime));
		ui.ticketResultTable->setItem(row, 4, new QTableWidgetItem(arriveTime));
		ui.ticketResultTable->setItem(row, 5, new QTableWidgetItem(QString::number(businessRemain)));
		ui.ticketResultTable->setItem(row, 6, new QTableWidgetItem(QString::number(firstRemain)));
		ui.ticketResultTable->setItem(row, 7, new QTableWidgetItem(QString::number(secondRemain)));
		ui.ticketResultTable->setItem(row, 8, new QTableWidgetItem(priceStr));
		// 添加购票按钮到第9列
		QPushButton* buyBtn = new QPushButton("购票");
		ui.ticketResultTable->setCellWidget(row, 9, buyBtn);
		connect(buyBtn, &QPushButton::clicked, this, [this, row]() { this->onBuyTicketClicked(row); });
		found = true;
	}

	if (!found) {
		QMessageBox::information(this, "无余票", "未找到符合条件的余票。");
	}
}

void Purchase_Ticket_Search::onBuyTicketClicked(int row)
{
	// 填充bookTicketPOJO
	bookTicket = new bookTicketPOJO();
	bookTicket->setTrainCode(ui.ticketResultTable->item(row, 0)->text().toStdString());
	bookTicket->setStartStation(ui.ticketResultTable->item(row, 1)->text().toStdString());
	bookTicket->setEndStation(ui.ticketResultTable->item(row, 2)->text().toStdString());
	bookTicket->setDepartTime(ui.ticketResultTable->item(row, 3)->text().toStdString());
	bookTicket->setArriveTime(ui.ticketResultTable->item(row, 4)->text().toStdString());
	bookTicket->setTimeCost(ui.ticketResultTable->item(row, 5)->text().toStdString());
	// 设置购票详情页的乘车日期为查询时的日期
	bookTicket->setTravelDate(ui.dateEdit->date().toString("yyyy-MM-dd").toStdString());
	// 弹出购票窗口
	bookTicketShowWindow = new Book_Ticket_Show_Window();
	int result = bookTicketShowWindow->exec();
	// 购票窗口关闭后刷新余票显示
	onQueryTickets();
}

